package com.myCompany.edu.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.myCompany.edu.realtime.app.BaseAppV1;
import com.myCompany.edu.realtime.bean.TradeCartAddUUBean;
import com.myCompany.edu.realtime.common.Constant;
import com.myCompany.edu.realtime.util.AtguiguUtil;
import com.myCompany.edu.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

public class Dws06_DwsTradeCartAdd extends BaseAppV1 {

    public static void main(String[] args) {
        new Dws06_DwsTradeCartAdd().init(
                4006,
                2,
                "Dws06_dwsTradeCartAdd",
                Constant.TOPIC_DWD_TRAFFIC_ACTION
        );
    }

    @Override
    protected void handle(StreamExecutionEnvironment env,
                          DataStreamSource<String> stream) {
        //过滤加购数据
        SingleOutputStreamOperator<JSONObject> filterStream = filterCarAdd(stream);
        //filterStream.print();
        //封装到 bean 中
        SingleOutputStreamOperator<TradeCartAddUUBean> beanStream = parseToBean(filterStream);
        //beanStream.print();
        //开窗聚合
        SingleOutputStreamOperator<TradeCartAddUUBean> resultStream = windowAndAgg(beanStream);
        //resultStream.print();
        //写进clickhouse
        writeToClickHouse(resultStream);

    }

    private void writeToClickHouse(SingleOutputStreamOperator<TradeCartAddUUBean> resultStream) {
        resultStream.addSink(FlinkSinkUtil.getClickHouseSink("dws_trade_cart_add_window", TradeCartAddUUBean.class));
    }

    private SingleOutputStreamOperator<TradeCartAddUUBean> windowAndAgg(SingleOutputStreamOperator<TradeCartAddUUBean> beanStream) {
        return beanStream
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<TradeCartAddUUBean>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                                .withTimestampAssigner((bean,ts) -> bean.getTs())
                )
                .windowAll(TumblingEventTimeWindows.of(Time.seconds(5)))
                .reduce(new ReduceFunction<TradeCartAddUUBean>() {
                            @Override
                            public TradeCartAddUUBean reduce(TradeCartAddUUBean bean1,
                                                             TradeCartAddUUBean bean2) throws Exception {
                                bean1.setCartAddUuCt(bean1.getCartAddUuCt() + bean2.getCartAddUuCt());
                                return bean1;
                            }
                        },
                        new ProcessAllWindowFunction<TradeCartAddUUBean, TradeCartAddUUBean, TimeWindow>() {

                            @Override
                            public void process(Context context,
                                                Iterable<TradeCartAddUUBean> iterable,
                                                Collector<TradeCartAddUUBean> out) throws Exception {
                                TradeCartAddUUBean bean = iterable.iterator().next();
                                bean.setStt(AtguiguUtil.toDateTime(context.window().getStart()));
                                bean.setEdt(AtguiguUtil.toDateTime(context.window().getEnd()));
                                out.collect(bean);
                            }
                        }
                );
    }

    private SingleOutputStreamOperator<TradeCartAddUUBean> parseToBean(SingleOutputStreamOperator<JSONObject> stream) {
        return stream
                .keyBy(object -> object.getString("uid"))
                .process(new KeyedProcessFunction<String, JSONObject, TradeCartAddUUBean>() {

                    private ValueState<String> userState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        userState = getRuntimeContext().getState(new ValueStateDescriptor<String>("userState", String.class));

                    }

                    @Override
                    public void processElement(JSONObject obj,
                                               Context context,
                                               Collector<TradeCartAddUUBean> out) throws Exception {

                        String actionId = obj.getString("action_id");

                        Long cartAddUuCt =0L;

                        Long ts = obj.getLong("ts");
                        String today = AtguiguUtil.toDate(ts);
                        if ("cart_add".equals(actionId) && !today.equals(userState.value())){
                            userState.update(today);
                            cartAddUuCt = 1L;
                        }
                        out.collect(new TradeCartAddUUBean(
                                "","",
                                cartAddUuCt,ts
                        ));
                    }
                });
    }

    private SingleOutputStreamOperator<JSONObject> filterCarAdd(DataStreamSource<String> stream) {
        return stream
                .map(JSON::parseObject)
                .filter(object -> {
                    return "cart_add".equals(object.getString("action_id"));
                    });


    }
}
